package com.lyn.module_custom_camera;

import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.media.FaceDetector;

/**
 * created by lyn at 2021/10/25
 */
public class FaceHelper {

    private static final String TAG = "FaceHelper";

    private static class FaceHelperTypeClass {
        private static FaceHelper instance = new FaceHelper();
    }

    public static FaceHelper getInstance() {
        return FaceHelperTypeClass.instance;
    }

    private FaceDetector faceDetector;
    private FaceDetector.Face[] faces;
    private int width;
    private int height;

    //初始化谷歌自带人脸检测算法
    public void initGoogleFaceDetector(int width, int height) {
        this.width = width;
        this.height = height;
        faceDetector = new FaceDetector(width, height, 1);
        faces = new FaceDetector.Face[1];
    }

    /**
     * 谷歌自带人脸检测算法
     *
     * @param bitmap
     * @return
     */
    public Rect googleFaceDetector(Bitmap bitmap) {
        if (bitmap == null) return null;
        if (bitmap.getWidth() != width || bitmap.getHeight() != height) {
            initGoogleFaceDetector(bitmap.getWidth(), bitmap.getHeight());
        }
        Bitmap copy = bitmap.copy(Bitmap.Config.RGB_565, true);
        int faceCount = faceDetector.findFaces(copy, faces);
        if (faceCount < 1) return null;
        FaceDetector.Face face = faces[0];
        if (face == null) return null;
        PointF pointF = new PointF();
        float confidence = face.confidence();
        face.getMidPoint(pointF);
        Point point = new Point();
        point.set((int) pointF.x, (int) pointF.y);
        int eyesDistance = (int) face.eyesDistance();
        Rect rect = new Rect();
        rect.left = point.x - eyesDistance / 2 * 3;
        rect.top = point.y - eyesDistance / 2 * 3;
        rect.right = point.x + eyesDistance / 2 * 3;
        rect.bottom = point.y + eyesDistance / 2 * 3;

        rect.left = rect.left % 2 == 0 ? rect.left : rect.left - 1;
        rect.top = rect.top % 2 == 0 ? rect.top : rect.top - 1;
        rect.right = rect.right % 2 == 0 ? rect.right : rect.right - 1;
        rect.bottom = rect.bottom % 2 == 0 ? rect.bottom : rect.bottom - 1;
        return rect;
    }
}
